package com.example.happytime;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.happytime.JokeBean.ResultBean;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class JokeFragment extends BaseFragment {


    PullToRefreshListView jokeLv;
    List<String> data;
    ArrayAdapter<String> adapter;
    int page = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
      View view = inflater.inflate(R.layout.fragment_joke2, container, false);
      jokeLv = view.findViewById(R.id.joke_1v);
      data = new ArrayList<>();
      adapter = new ArrayAdapter<>(getContext(),R.layout.iten_joke,R.id.item_joke_tv,data);
      jokeLv.setAdapter(adapter);
      String url = getJokeUrl(page);
      connectNet(url);
      setRefresh();
      return view;
    }

//上拉加载
    Handler handler = new Handler(){
        public void handleMessage(Message msg){
            jokeLv.onRefreshComplete();//刷新完成，进度条不显示
        }
};
    private void setRefresh() {
        jokeLv.setMode(PullToRefreshBase.Mode.BOTH);
        jokeLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                handler.sendEmptyMessageDelayed(1,500);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                String jokeUrl = getJokeUrl(page);
                connectNet(jokeUrl);
            }
        });
    }

    //
    private String getJokeUrl(int page) {
        String key ="680ca9398eb1a6304d1ab411b66e58a1";
        String url = "http://v.juhe.cn/joke/content/list.php?key="+key+"&page="+page+"&pagesize=10&sort=asc&time=1418745237";
        return url;
    }

    @Override
    public void onSuccess(String result) {
        Log.i("lsh", "onSuccess: result==="+result);
        JokeBean jokeBean = new Gson().fromJson(result, JokeBean.class);
        List<ResultBean.DataBean> list = jokeBean.getResult().getData();
        Log.i("lsh", "onSuccess:size "+list.size());
        for (int i = 0;i < list.size();i++){
            String s = list.get(i).getContent();
            data.add(s);
        }
        Log.i("lsh", "onSuccess:size "+data.size());
        adapter.notifyDataSetChanged();
        jokeLv.onRefreshComplete();

    }
}
